﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using SS.Net.AppGen.Models;
using SS.Common.DBBuilder.DBDataStructure;
using SS.Common.Logging;

namespace SS.Net.AppGen.WebGenerators.WebViewGenerator
{
    /// <summary>
    /// The algorithm to generate the list view items for user table
    /// </summary>
    [Export(typeof(InsertViewItemByUserAlgorithm))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class InsertViewItemByUserAlgorithm : BaseInsertViewItemAlgorithm
    {
        /// <summary>
        /// The logger instance
        /// </summary>
        private readonly ILogger Logger = LoggerManager.GetLogger(typeof(InsertViewItemByUserAlgorithm).Name);

        /// <summary>
        /// The default constructor
        /// </summary>
        public InsertViewItemByUserAlgorithm()
        {
            this.XMLTemplate = "PartialInsertViewItemByUser.xml";
            this.DeserializeTemplate();
        }

        /// <summary>
        /// Generate the contents of list view items
        /// </summary>
        /// <param name="tbl"></param>
        public override void GenerateContents(Table tbl)
        {
            this.Logger.InfoFormat("Generate InsertView[{0}] --> Start", tbl.Name);

            try
            {
                var contents = new StringBuilder(BaseConsts.MAX_BYTES);
                var htmlContents = this.ViewComponents.HtmlContent.Replace(BaseConsts.ConstTable, tbl.Name)
                    .Replace(BaseConsts.ConstGlobalNameSpace, WebConfiguration.Instance.NameSpace);

                contents.AppendLine(htmlContents);

                // Init path
                this.DirPath = Path.Combine(this.GetAppPath(), "WebGenerator", "Views", tbl.Name + "Manager");
                this.InitializeDir(this.DirPath, false);
                // Save contents to a file
                this.SaveFile(contents.ToString().TrimStart(), "_PartialInsert.cshtml");
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat("GenerateContents Error: {0}", ex.ToString());
                throw new Exception(ex.ToString());
            }

            this.Logger.InfoFormat("Generate InsertView[{0}] <-- End", tbl.Name);
        }
    }
}
